package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.vo.UcenterMember;
import com.atguigu.eduservice.client.UcenterClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.eduservice.entity.vo.CourseInfoVo;
import com.atguigu.eduservice.service.EduCommentService;
import com.atguigu.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-09-16
 */
@RestController
@RequestMapping("/eduservice/comment")
@CrossOrigin
@EnableFeignClients
public class EduCommentController {

    @Autowired
    private EduCommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    @Autowired
    private EduCourseService courseService;

    //分页查询课程评论的方法
    @GetMapping("getCommentList/{courseId}/{page}/{limit}")
    public R getCommentList(@PathVariable String courseId,@PathVariable Long page,@PathVariable Long limit){
        Page<EduComment> pageComment=new Page<>(page,limit);
        Map<String,Object> map=commentService.getCommentList(pageComment,courseId);
        return R.ok().data(map);
    }

    //添加评论的方法
    @PostMapping("auth/save")
    public R saveComment(@RequestBody EduComment eduComment,HttpServletRequest request){
        String memberId= JwtUtils.getMemberIdByJwtToken(request);
        String courseId=eduComment.getCourseId();
        CourseInfoVo courseInfo = courseService.getCourseInfo(courseId);
        String teacherId = courseInfo.getTeacherId();
        if(StringUtils.isEmpty(memberId)){
            return R.error().code(28004).message("请先登录再评论");
        }
        eduComment.setTeacherId(teacherId);
        eduComment.setMemberId(memberId);
        UcenterMember member = ucenterClient.getMemberInfo(memberId);
        eduComment.setNickname(member.getNickname());
        eduComment.setAvatar(member.getAvatar());

        commentService.save(eduComment);

        return R.ok();
    }
}

